package com.cass.controller;

import com.cass.entity.Teacher;
import com.cass.entity.Token;
import com.cass.service.TeacherService;
import com.cass.uilts.JwtUtil;
import com.cass.uilts.Result;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.logging.Logger;
import org.mybatis.logging.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RequestMapping("/teacher")
@RestController
@RequiredArgsConstructor
@Slf4j
public class TeacherController {
  private static final Logger logger = LoggerFactory.getLogger( TeacherController.class);
  private final TeacherService teacherService;
  @PostMapping()
    public Result<?> login(@RequestBody Teacher teacher) {
        // 验证用户名和密码
        Teacher dbUser = teacherService.getUserByUsernameAndPassword(teacher.getUsername(), teacher.getPassword());
        if (dbUser == null) {
           return Result.error("用户名或密码错误");
        }

        // 创建要放入 JWT 的 claims
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", dbUser.getId());
        claims.put("username", dbUser.getUsername());

        // 生成 JWT token
        String data = JwtUtil.generate(claims);
        Token token = new Token(teacher.getUsername(),data);
        // 返回 token
        return Result.success(token);
    }
    @PostMapping("/register")
    public Result<?> register(@RequestBody Teacher teacher) {
        // 验证用户名和密码
        Teacher dbUser = teacherService.getUserByUsernameAndPassword(teacher.getUsername(), teacher.getPassword());
        if (dbUser != null) {
            return Result.error("用户名已存在");
        }
        teacherService.save(teacher);
        return Result.success("注册成功");
    }
}
